<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="聚焦Java性能优化 打造亿级流量秒杀系统,">










<meta name="description" content="本文为慕课网 《聚焦Java性能优化 打造亿级流量秒杀系统》视频教程的学习笔记实战视频地址： https://coding.imooc.com/class/chapter/338.html前期免费视频地址： http://www.imooc.com/learn/1079代码地址：https://gitee.com/aiolos123/secondkill">
<meta name="keywords" content="聚焦Java性能优化 打造亿级流量秒杀系统">
<meta property="og:type" content="article">
<meta property="og:title" content="【二】聚焦Java性能优化 打造亿级流量秒杀系统——企业级开发注意事项和通用开发步骤、通用对象">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2020/01/20/second-kill-system-step-by-step-2/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文为慕课网 《聚焦Java性能优化 打造亿级流量秒杀系统》视频教程的学习笔记实战视频地址： https://coding.imooc.com/class/chapter/338.html前期免费视频地址： http://www.imooc.com/learn/1079代码地址：https://gitee.com/aiolos123/secondkill">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200121092142950.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200120154828887.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200121093803996.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200121120159492.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200122064721286.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200120150818472.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200120170537771.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200121094335873.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200121100721688.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200121105001345.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200121113353302.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200121115117372.jpg">
<meta property="og:updated_time" content="2020-01-27T05:59:47.029Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【二】聚焦Java性能优化 打造亿级流量秒杀系统——企业级开发注意事项和通用开发步骤、通用对象">
<meta name="twitter:description" content="本文为慕课网 《聚焦Java性能优化 打造亿级流量秒杀系统》视频教程的学习笔记实战视频地址： https://coding.imooc.com/class/chapter/338.html前期免费视频地址： http://www.imooc.com/learn/1079代码地址：https://gitee.com/aiolos123/secondkill">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20200121092142950.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2020/01/20/second-kill-system-step-by-step-2/">





  <title>【二】聚焦Java性能优化 打造亿级流量秒杀系统——企业级开发注意事项和通用开发步骤、通用对象 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2020/01/20/second-kill-system-step-by-step-2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【二】聚焦Java性能优化 打造亿级流量秒杀系统——企业级开发注意事项和通用开发步骤、通用对象</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-01-20T05:59:13+08:00">
                2020-01-20
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/SpringBoot/" itemprop="url" rel="index">
                    <span itemprop="name">SpringBoot</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文为慕课网 《聚焦Java性能优化 打造亿级流量秒杀系统》视频教程的学习笔记<br>实战视频地址： <a href="https://coding.imooc.com/class/chapter/338.html" target="_blank" rel="noopener">https://coding.imooc.com/class/chapter/338.html</a><br>前期免费视频地址： <a href="http://www.imooc.com/learn/1079" target="_blank" rel="noopener">http://www.imooc.com/learn/1079</a><br>代码地址：<a href="https://gitee.com/aiolos123/secondkill" target="_blank" rel="noopener">https://gitee.com/aiolos123/secondkill</a></p>
<a id="more"></a>

<h2 id="企业级SpringBoot应用使用MVC模式开发注意事项"><a href="#企业级SpringBoot应用使用MVC模式开发注意事项" class="headerlink" title="企业级SpringBoot应用使用MVC模式开发注意事项"></a>企业级SpringBoot应用使用MVC模式开发注意事项</h2><p>在企业级SpringBoot应用开发中，需要严格遵守MVC模式的分层思想：</p>
<blockquote>
<ol>
<li>DataObject(即DO，是数据模型)是与数据库表中的字段完全一一映射，不含有逻辑; 一定不能将DO对象传递到前端；如下图：</li>
</ol>
</blockquote>
<p><img src="/blog/images/20200121092142950.jpg" alt="DataObject与数据库表中的字段完全一一映射"></p>
<blockquote>
<ol start="2">
<li>在Service层必须定义一个Model(是领域模型)，它才是MVC中业务模型交互的对象，也是处理业务的核心模型对象。如下图：</li>
<li>在Service层将多个DO对象封装为Model对象。因为DO是完全按照数据库表创建的，但并不一定是业务领域真正需要的模型，所以需要将多个DO对象封装为一个Model对象，而这个Model对象才是处理业务领域真正需要的模型。</li>
</ol>
</blockquote>
<p><img src="/blog/images/20200120154828887.jpg" alt="Model才是MVC中业务模型交互的对象"></p>
<blockquote>
<ol start="4">
<li>在Controller层中，将Model对象组装为ViewObject(VO)对象, 并将其返回给前端。而一定不能将领域模型Model对象传递到前端，因为前端仅仅需要展示的数据字段即可，而不能将业务对象Model完全返回到前端，如下图：</li>
</ol>
</blockquote>
<p><img src="/blog/images/20200121093803996.jpg" alt="将Model对象组装为ViewObject(VO)对象"></p>
<p><strong>注意：BeanUtils.copyProperties()方法要求copy的两个对象的属性名和类型必须完全一致！</strong></p>
<blockquote>
<ol start="5">
<li>统一异常处理的处理流程：只要程序出现跑不下去的异常都统一抛出BusinessException的子类，最终在Controller层中被SpringBoot的一个handler捕捞并做处理，代码如下</li>
</ol>
</blockquote>
<p><img src="/blog/images/20200121120159492.jpg" alt="统一异常处理的处理流程"></p>
<blockquote>
<ol start="6">
<li>定义统一的后端返回JSON数据格式对象, 如CommonReturnType类</li>
<li>定义统一的后端错误和异常数据格式对象，如包装器业务异常类实现：BusinessException、EmBusinessError都共同实现了CommonError接口</li>
</ol>
</blockquote>
<blockquote>
<ol start="8">
<li>在设计数据库时，尽量使用not null(注意：多条null也是不影响唯一索引的)，并设置默认值。 因为java处理空指针本身就脆弱，而且null对用户无意义。 如下图：</li>
</ol>
</blockquote>
<p><img src="/blog/images/20200122064721286.jpg" alt="尽量使用not null"></p>
<blockquote>
<ol start="9">
<li>先设计数据库表，还是<strong>先设计领域模型</strong>————高级人才会先设计需求对应的领域模型，而不是数据库表，只有初级人员才会按照UI需求先设计数据库表。</li>
</ol>
</blockquote>
<blockquote>
<ol start="10">
<li>企业级开发中需要注意的一点：尽可能保证Controller简单，而把业务处理都封装到Service中；</li>
<li>企业级开发中：一般定义Model层对象的属性都与VO层对象不同，而且VO层都有聚合操作，其中包含的信息也比较多</li>
</ol>
</blockquote>
<h2 id="企业级SpringBoot应用使用MVC模式开发的一般流程"><a href="#企业级SpringBoot应用使用MVC模式开发的一般流程" class="headerlink" title="企业级SpringBoot应用使用MVC模式开发的一般流程"></a>企业级SpringBoot应用使用MVC模式开发的一般流程</h2><blockquote>
<p>以使用MVC方式开发用户信息为例</p>
</blockquote>
<ol>
<li><p>创建Controller、Service包<br><img src="/blog/images/20200120150818472.jpg" alt="创建Controller、Service包"></p>
</li>
<li><p>编写UserController</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="meta">@RequestMapping(<span class="meta-string">"/user"</span>)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> IUserService userService;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 调用service服务获取对应id的用户对象并返回给前端</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id url中名为id的参数，用户id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@RequestMapping(<span class="meta-string">"/get"</span>)</span></span><br><span class="line">    <span class="meta">@ResponseBody</span></span><br><span class="line">    <span class="keyword">public</span> UserVO getUser(<span class="meta">@RequestParam(name = <span class="meta-string">"id"</span>)</span> Integer id)&#123;</span><br><span class="line">        <span class="comment">//调用service服务获取对应id的用户对象并返回给前端</span></span><br><span class="line">        UserModel userModel = userService.getUserById(id);</span><br><span class="line">        <span class="comment">//将核心领域模型用户对象转化为可供UI使用的viewobject对象</span></span><br><span class="line">        UserVO userVO = convertFromModel(userModel);</span><br><span class="line">        <span class="keyword">return</span> userVO;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> UserVO convertFromModel(UserModel userModel)&#123;</span><br><span class="line">        <span class="keyword">if</span>(userModel == <span class="literal">null</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        UserVO userVO = new UserVO();</span><br><span class="line">        BeanUtils.copyProperties(userModel, userVO);</span><br><span class="line">        <span class="keyword">return</span> userVO;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>编写Service接口和实现类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">IUserService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//通过用户id获取用户对象</span></span><br><span class="line">    <span class="function">UserModel <span class="title">getUserById</span><span class="params">(Integer id)</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserServiceImpl</span> <span class="keyword">implements</span> <span class="title">IUserService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserDOMapper userDOMapper;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserPasswordDOMapper userPasswordDOMapper;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> UserModel <span class="title">getUserById</span><span class="params">(Integer id)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//调用userDOMapper获取到对应的用户对象</span></span><br><span class="line">        UserDO userDO = userDOMapper.selectByPrimaryKey(id);</span><br><span class="line">        <span class="comment">//在企业级应用开发中，UserDO是一定不能传递到前端的</span></span><br><span class="line">        <span class="keyword">if</span>(userDO == <span class="keyword">null</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//通过用户id获取用户加密密码信息</span></span><br><span class="line">        UserPasswordDO userPasswordDO = userPasswordDOMapper.selectByUserId(userDO.getId());</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> convertFromDataObject(userDO, userPasswordDO);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 将userDao和userPasswordDO对象组装为一个UserModel对象</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> userDao</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> userPasswordDO</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> UserModel <span class="title">convertFromDataObject</span><span class="params">(UserDO userDao, UserPasswordDO userPasswordDO)</span></span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(userDao == <span class="keyword">null</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        UserModel userModel = <span class="keyword">new</span> UserModel();</span><br><span class="line">        BeanUtils.copyProperties(userDao, userModel);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(userPasswordDO != <span class="keyword">null</span>)&#123;</span><br><span class="line">            userModel.setEncrptPassword(userPasswordDO.getEncrptPassword());</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> userModel;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>启动项目，输入<a href="http://localhost:8080/user/get?id=1，查看返回Model对象的数据" target="_blank" rel="noopener">http://localhost:8080/user/get?id=1，查看返回Model对象的数据</a><br><img src="/blog/images/20200120170537771.jpg" alt="返回Model对象的数据"></p>
</li>
</ol>
<p>再查看返回VO对象的数据<br><img src="/blog/images/20200121094335873.jpg" alt="查看返回VO对象的数据"></p>
<p>至此，企业级SpringBoot应用使用MVC模式开发的一般流程完成！</p>
<h2 id="定义通用的返回对象"><a href="#定义通用的返回对象" class="headerlink" title="定义通用的返回对象"></a>定义通用的返回对象</h2><ol>
<li><p>按照上述的开发，由于不同Controller方法返回的JSON格式不同，所以前端无法采用通用的格式来处理这些JSON，因此在企业级开发中，后端需要统一返回JSON的格式，尤其是请求错误时要返回有意义的信息。</p>
</li>
<li><p>定义后端统一的JSON返回格式为：</p>
<figure class="highlight fortran"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">//若<span class="keyword">status</span>=success,则<span class="keyword">data</span>内返回前端需要的JSON数据</span><br><span class="line">//若<span class="keyword">status</span>=fail，则<span class="keyword">data</span>内使用通用的错误码格式</span><br><span class="line">&#123;<span class="keyword">status</span>:<span class="string">''</span>,<span class="keyword">data</span>:<span class="string">''</span>&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>编写后端统一的JSON返回格式对象</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 返回给前端的统一JSON结果格式</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> CommonReturnType &#123;</span><br><span class="line">    <span class="comment">//表明对应请求的返回处理结果，值为"success"或"fail"</span></span><br><span class="line">    <span class="keyword">private</span> <span class="built_in">String</span> status;</span><br><span class="line">    <span class="comment">//若status=success,则data内返回前端需要的JSON数据</span></span><br><span class="line">    <span class="comment">//若status=fail，则data内使用通用的错误码格式</span></span><br><span class="line">    <span class="keyword">private</span> <span class="built_in">Object</span> data;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//定义一个返回成功数据的方法</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> CommonReturnType success(<span class="built_in">Object</span> result)&#123;</span><br><span class="line">        <span class="keyword">return</span> CommonReturnType.create(result, <span class="string">"success"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//定义一个返回失败数据的方法</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> CommonReturnType fail(<span class="built_in">Object</span> result)&#123;</span><br><span class="line">        <span class="keyword">return</span> CommonReturnType.create(result, <span class="string">"fail"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//定义一个通用的创建方法</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> CommonReturnType create(<span class="built_in">Object</span> result, <span class="built_in">String</span> status)&#123;</span><br><span class="line">        CommonReturnType <span class="keyword">type</span> = <span class="keyword">new</span> CommonReturnType();</span><br><span class="line">        <span class="keyword">type</span>.setStatus(status);</span><br><span class="line">        <span class="keyword">type</span>.setData(result);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">type</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="定义通用的返回对象——返回正确信息"><a href="#定义通用的返回对象——返回正确信息" class="headerlink" title="定义通用的返回对象——返回正确信息"></a>定义通用的返回对象——返回正确信息</h3><ol>
<li><p>修改Controller的方法的返回值，返回CommonReturnType对象</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(<span class="meta-string">"/get"</span>)</span></span><br><span class="line"><span class="meta">@ResponseBody</span></span><br><span class="line"><span class="keyword">public</span> CommonReturnType getUser(<span class="meta">@RequestParam(name = <span class="meta-string">"id"</span>)</span> Integer id)&#123;</span><br><span class="line">    <span class="comment">//调用service服务获取对应id的用户对象并返回给前端</span></span><br><span class="line">    UserModel userModel = userService.getUserById(id);</span><br><span class="line">    <span class="comment">//将核心领域模型用户对象转化为可供UI使用的viewobject对象</span></span><br><span class="line">    UserVO userVO = convertFromModel(userModel);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//返回通用对象</span></span><br><span class="line">    <span class="keyword">return</span> CommonReturnType.success(userVO);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>启动项目，查看返回成功的数据<br><img src="/blog/images/20200121100721688.jpg" alt="查看返回成功的数据"></p>
</li>
</ol>
<h3 id="定义通用的返回对象——返回错误或异常信息"><a href="#定义通用的返回对象——返回错误或异常信息" class="headerlink" title="定义通用的返回对象——返回错误或异常信息"></a>定义通用的返回对象——返回错误或异常信息</h3><p>上述是返回成功数据的格式，如果是返回错误或异常数据呢？</p>
<ol>
<li><p>若status=fail，则data内使用通用的错误码格式，定义其格式为</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;<span class="attribute">errCode</span>:<span class="string">''</span>,errMsg:<span class="string">''</span>&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>编写后端统一的通用的错误码格式枚举类</p>
<figure class="highlight aspectj"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 通用的错误码格式接口</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">CommonError</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">int</span> <span class="title">getErrCode</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="function">String <span class="title">getErrMsg</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="function">CommonError <span class="title">setErrMsg</span><span class="params">(String msg)</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 通用的错误码格式枚举类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">enum</span> EmBusinessError <span class="keyword">implements</span> CommonError &#123;</span><br><span class="line">    <span class="comment">//00001 通用错误类型</span></span><br><span class="line">    PARAMETER_VALIDTION_ERROR(<span class="number">00001</span>, <span class="string">"参数不合法"</span>),</span><br><span class="line">    <span class="comment">//10000开头为用户信息相关错误定义</span></span><br><span class="line">    USER_NOT_EXIST(<span class="number">10001</span>, <span class="string">"用户不存在"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> errCode;</span><br><span class="line">    <span class="keyword">private</span> String errMsg;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">EmBusinessError</span><span class="params">(<span class="keyword">int</span> errCode, String errMsg)</span></span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.errCode = errCode;</span><br><span class="line">        <span class="keyword">this</span>.errMsg = errMsg;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">int</span> <span class="title">getErrCode</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.errCode;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function">String <span class="title">getErrMsg</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.errMsg;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 定制化的改动通用错误类型的errMsg</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> msg</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function">CommonError <span class="title">setErrMsg</span><span class="params">(String msg)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.errMsg = msg;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>自定义通用异常类</p>
<blockquote>
<p>企业级开发过程中统一异常处理的处理流程：只要程序出现跑不下去的异常都统一抛出自定义通用异常类，最终在Controller层中被SpringBoot的一个handler捕获并做处理</p>
</blockquote>
</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 自定义通用异常类</span></span><br><span class="line"><span class="comment"> * 包装器业务异常类实现：BusinessException、EmBusinessError都共同实现了CommonError接口</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BusinessException</span> <span class="keyword">extends</span> <span class="title">Exception</span> <span class="keyword">implements</span> <span class="title">CommonError</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> CommonError commonError;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 直接接收EmBusinessError的传参用于构造业务异常</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> commonError</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BusinessException</span><span class="params">(CommonError commonError)</span></span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(); <span class="comment">//Exception的初始化</span></span><br><span class="line">        <span class="keyword">this</span>.commonError = commonError;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 接收自定义errMsg的方法构造业务异常</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> commonError</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> errMsg</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BusinessException</span><span class="params">(CommonError commonError, String errMsg)</span></span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(); <span class="comment">//Exception的初始化</span></span><br><span class="line">        <span class="keyword">this</span>.commonError = commonError;</span><br><span class="line">        <span class="keyword">this</span>.commonError.setErrMsg(errMsg);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getErrCode</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.commonError.getErrCode();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getErrMsg</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.commonError.getErrMsg();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> CommonError <span class="title">setErrMsg</span><span class="params">(String msg)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.commonError.setErrMsg(msg);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="4">
<li><p>使用BusinessException返回异常信息</p>
<figure class="highlight aspectj"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/get"</span>)</span><br><span class="line"><span class="meta">@ResponseBody</span></span><br><span class="line"><span class="keyword">public</span> CommonReturnType getUser(<span class="meta">@RequestParam</span>(name = <span class="string">"id"</span>) Integer id) <span class="keyword">throws</span> BusinessException &#123;</span><br><span class="line">    <span class="comment">//调用service服务获取对应id的用户对象并返回给前端</span></span><br><span class="line">    UserModel userModel = userService.getUserById(id);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//若获取的对应用户信息不存在，则抛出BusinessException异常</span></span><br><span class="line">    <span class="keyword">if</span>(userModel == <span class="keyword">null</span>)&#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> BusinessException(EmBusinessError.USER_NOT_EXIST);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//将核心领域模型用户对象转化为可供UI使用的viewobject对象</span></span><br><span class="line">    UserVO userVO = convertFromModel(userModel);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//返回通用对象</span></span><br><span class="line">    <span class="function"><span class="keyword">return</span> CommonReturnType.<span class="title">success</span><span class="params">(userVO)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>启动项目，查看返回错误的数据<br><img src="/blog/images/20200121105001345.jpg" alt="查看返回错误的数据"></p>
</li>
</ol>
<p>出现上述页面，是因为controller方法抛出的BusinessException异常直接抛出到Tomcat容器中，而Tomcat容器处理异常的方法很简单，就是给一个500的错误页面。</p>
<ol start="6">
<li>解决办法是：SpringBoot提供的通用解决异常的方法————使用SpringBoot自带的ExceptionHandler来拦截Tomcat的异常处理方式，进行自定义的通用异常处理，代码如下：</li>
</ol>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>通用Controller基类，其他Controller类都需继承该类</span></span></span><br><span class="line"><span class="comment"><span class="markdown"> */</span></span></span><br><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">BaseController</span> </span>&#123;</span><br><span class="line">    <span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>SpringBoot提供的通用解决异常的方法：</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>定义exceptionhandler来解决未被controller层吸收的exception异常</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param request</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param ex</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@return</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="code">     */</span></span></span></span><br><span class="line">    <span class="meta">@ExceptionHandler</span>(Exception.<span class="keyword">class</span>) <span class="comment">//通过@ExceptionHandler注解来指定要捕获并处理的异常</span></span><br><span class="line">    <span class="meta">@ResponseStatus</span>(HttpStatus.OK) <span class="comment">//处理完异常后，最终返回到前端的响应状态</span></span><br><span class="line">    <span class="meta">@ResponseBody</span></span><br><span class="line">    public CommonReturnType handlerException(HttpServletRequest request, Exception ex)&#123;</span><br><span class="line">        <span class="built_in">Map</span>&lt;<span class="built_in">String</span>,<span class="built_in">Object</span>&gt; respData = <span class="keyword">new</span> HashMap&lt;<span class="built_in">String</span>, <span class="built_in">Object</span>&gt;();</span><br><span class="line">        <span class="keyword">if</span>(ex instanceof BusinessException)&#123;</span><br><span class="line">            <span class="comment">//过滤掉无用的异常信息</span></span><br><span class="line">            BusinessException bex = (BusinessException)ex;</span><br><span class="line">            respData.put(<span class="string">"errCode"</span>, bex.getErrCode());</span><br><span class="line">            respData.put(<span class="string">"errMsg"</span>, bex.getErrMsg());</span><br><span class="line">        &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">            respData.put(<span class="string">"errCode"</span>, EmBusinessError.UNKNOWN_ERROR.getErrCode());</span><br><span class="line">            respData.put(<span class="string">"errMsg"</span>, EmBusinessError.UNKNOWN_ERROR.getErrMsg());</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> CommonReturnType.fail(respData);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="7">
<li><p>启动项目，查看返回错误的数据<br><img src="/blog/images/20200121113353302.jpg" alt="查看返回错误的数据"></p>
</li>
<li><p>启动项目，查看返回异常的数据<br><img src="/blog/images/20200121115117372.jpg" alt="查看返回异常的数据"></p>
</li>
</ol>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/聚焦Java性能优化-打造亿级流量秒杀系统/" rel="tag"># 聚焦Java性能优化 打造亿级流量秒杀系统</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2020/01/19/second-kill-system-step-by-step-1/" rel="next" title="【一】聚焦Java性能优化 打造亿级流量秒杀系统——搭建电商秒杀项目">
                <i class="fa fa-chevron-left"></i> 【一】聚焦Java性能优化 打造亿级流量秒杀系统——搭建电商秒杀项目
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2020/01/21/second-kill-system-step-by-step-3/" rel="prev" title="【三】聚焦Java性能优化 打造亿级流量秒杀系统——电商秒杀项目用户模型管理开发">
                【三】聚焦Java性能优化 打造亿级流量秒杀系统——电商秒杀项目用户模型管理开发 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#企业级SpringBoot应用使用MVC模式开发注意事项"><span class="nav-number">1.</span> <span class="nav-text">企业级SpringBoot应用使用MVC模式开发注意事项</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#企业级SpringBoot应用使用MVC模式开发的一般流程"><span class="nav-number">2.</span> <span class="nav-text">企业级SpringBoot应用使用MVC模式开发的一般流程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#定义通用的返回对象"><span class="nav-number">3.</span> <span class="nav-text">定义通用的返回对象</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#定义通用的返回对象——返回正确信息"><span class="nav-number">3.1.</span> <span class="nav-text">定义通用的返回对象——返回正确信息</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#定义通用的返回对象——返回错误或异常信息"><span class="nav-number">3.2.</span> <span class="nav-text">定义通用的返回对象——返回错误或异常信息</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
